import { baseUrl } from "/config";
import { request } from "/utils/request";
import { PageModule } from '/constants';
import parse from 'mini-html-parser2';
const app = getApp();
Page({
    data: {
        customNavHeight: 0,
        pageTopBgHeight: 250,
        path: baseUrl,
        content: [],
        swiperModule: { list: [], type: PageModule.SWIPER },
        catModule: { list: [], type: PageModule.CAT },
        verticalGoodsModule: { list: [], type: PageModule.VERTICALGOODS },
        horizontalGoodsModule: { list: [], type: PageModule.HORIZONTALGOODS },
        cats: [],
        catRows: 1,
        catColumns: 1,
        PageModule,
        current: 0
    },
    onLoad(query) {
        // 页面加载
        console.info(`Page onLoad with query: ${JSON.stringify(query)}`);
        const {
            statusBarHeight,
            titleBarHeight,
        } = app.globalData.sysInfo;
        this.setData({
            customNavHeight: statusBarHeight + titleBarHeight
        })
        this.getPageConfig();
        my.setCanPullDown({ canPullDown: false });
    },
    onReady() {
        // 页面加载完成
    },
    onShow() {
        // 页面显示
    },
    getCatList(list, rows = 1, columns = 1) {
        let arr = [];
        list.forEach(item => {
            if (!arr.length) {
                arr = [
                    [item]
                ];
            } else {
                if (arr[arr.length - 1].length < columns * rows) {
                    arr[arr.length - 1].push(item);
                } else {
                    arr.push([item]);
                }
            }
        });
        return arr;
    },
    async getPageConfig() {
        my.showLoading({ content: '加载中' });
        try {
            const { code, data: { content } } = await request.get('/miniapp/page/indexPage');
            if (code === 200) {
                const { SWIPER, CAT, VERTICALGOODS, HORIZONTALGOODS, RICHTEXT } = PageModule;
                const moduleList = [
                    { module: SWIPER, key: 'swiperModule' },
                    { module: CAT, key: 'catModule' },
                    { module: VERTICALGOODS, key: 'verticalGoodsModule' },
                    { module: HORIZONTALGOODS, key: 'horizontalGoodsModule' }
                ];
                const dataObj = moduleList.map(item => {
                    const findResult = content.find((item1, index) => { return item1.type === item.module });
                    return {
                        [item.key]: findResult || { type: moduleList[index].module, list: [] }
                    }
                }).reduce((pre,
                    item) => ({ ...pre, ...item }), {});
                const catModule = dataObj.catModule;
                dataObj.cats = this.getCatList(catModule.list, catModule.rows, catModule.columns);
                dataObj.catRows = catModule.rows;
                dataObj.catColumns = catModule.columns;
                dataObj.horizontalGoodsModule.list = dataObj.horizontalGoodsModule.list.map(item => ({
                    ...item,
                    displayPrice: this
                        .getDisplayPrice(item.sku)
                }));
                dataObj.verticalGoodsModule.list = dataObj.verticalGoodsModule.list.map(item => ({
                    ...item,
                    displayPrice: this
                        .getDisplayPrice(item.sku)
                }));
                const formattedContent = content.map(item => {
                    if ([HORIZONTALGOODS, VERTICALGOODS].includes(item.type)) {
                        item.displayPrice = this.getDisplayPrice(item.sku);
                    }
                    if (item.type === CAT) {
                        item.list = this.getCatList(item.list, item.rows, item.columns);
                    }
                    if (item.type === RICHTEXT && item.list.length) {
                        parse(item.list[0].text.replace(/<img/g, '<img style="width: 100%;"'), (err, nodes) => {
                            if (!err) item.list = [nodes];
                        })
                    }
                    return item;
                })
                setTimeout(() => {
                    this.setData({
                        content: formattedContent
                    })
                })
            }
        } finally {
            my.hideLoading();
        }
    },
    getDisplayPrice(sku) {
        if (!sku || !sku.length) return { price: ['0', '00'], originalPrice: '0.00' };
        const priceList = sku.map(({ price, originalPrice }) => ({ price, originalPrice })).sort((a, b) => a.price - b.price);
        const { price, originalPrice } = priceList[0];
        return {
            price: (price / 100).toFixed(2).split("."),
            originalPrice: (originalPrice / 100).toFixed(2),
        }
    },
    catSwiperChange(e) {
        this.setData({
            current: e.detail.current
        })
    },
    toDetail(e) {
        const { _id } = e.target.dataset;
        my.navigateTo({ url: '/pages/goodsDetail/goodsDetail?_id=' + _id });
    }
});